import com.alibaba.ttl.TransmittableThreadLocal;

import java.util.Date;
import java.util.Timer;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhangdi
 * @version 1.0
 * @date 2022.3.14 12:48
 */
public class ReentrantLockDemo {
    private static ReentrantLockDemo _this = new ReentrantLockDemo();
   public static ReentrantLockDemo getInst(){
        return _this;
    }

    public ReentrantLockDemo(){
       state = new TransmittableThreadLocal<>();
       state.set(0);
       data = new TransmittableThreadLocal<>();
       data.set(-1);
        shareData.set(0);
//       Thread thread = new Thread(new timer0());
//       thread.start();
        ScheduledThreadPoolExecutor service =new ScheduledThreadPoolExecutor(1);
        service.scheduleWithFixedDelay(new timer0(), 5, 5, TimeUnit.SECONDS);
    }

    final String s0 = "request";
    TransmittableThreadLocal<Integer> state;
    TransmittableThreadLocal<Integer> data;
    TransmittableThreadLocal<Integer> shareData = new TransmittableThreadLocal<>();
    Lock lock = new ReentrantLock(true);
    Thread thread;

    public void request(int i) {
        try {
            data.set(i);
            send(s0);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    public void send(String s) {
        try {
            if (state.get() == 1) {
                return;
            }
            state.set(1);
            add();
            System.out.println(" --- " + new Date()+" " +s + data.get() + "  " + shareData.get());
//            state.set(-1);
        } catch (Exception e) {
e.printStackTrace();
        } finally {
            data.remove();
            state.set(-1);
        }
    }

    private void add(){
        shareData.set(shareData.get()+1);
    }

    class timer0 implements Runnable{
        @Override
        public void run() {
            final String s1 = "timer";
            try {
                if (state.get() != 1) {
                    data.set(0);
                    send(s1);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
